using System.Security.Cryptography;
using System.Threading.Tasks;
using System;
using System.Web;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using blog.Models;
using blog.BLL;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Authorization;

namespace blog.Controllers 
{
    public class LoginController : BaseController 
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
        }

        [AllowAnonymous]
        public ActionResult index () 
        {
            if(GetCookies("save_account").Equals("true"))
            {
                ViewBag.user_account_save = GetCookies("user_account_save");
                ViewBag.user_password_save = GetCookies("user_password_save");
            } 
            else 
            {
                ViewBag.user_account_save = "";
                ViewBag.user_password_save = "";
            }
            ViewBag.save_account = GetCookies("save_account");

            return View ();
        }

        [HttpPost]
        public ActionResult loginAjax(string account, string password, bool saveAccount) 
        {
            UsersModel user = UserBLL.findByAccount(account);
            if(user != null && password.Equals(user.password)) {
                HttpContext.Session.SetString("user_account", user.account);
                HttpContext.Session.SetString("user_name", user.name);
                string token = generateToken(user.id + user.account);
                HttpContext.Session.SetString("access_token", token);
                SetCookies("access_token", token);
                if(saveAccount == true) {
                    SetCookies("save_account", "true");
                    SetCookies("user_account_save", user.account);
                    SetCookies("user_password_save", user.password);
                } else {
                    SetCookies("save_account", "false");
                    SetCookies("user_account_save", "");
                    SetCookies("user_password_save", "");
                }
                // Session["account"] = user.account;
                // Session["name"] = user.name;
                return result("/home/index", "", ResultModel.CODE_SUCCESS);;
            }
            
            return result(null, "用户名密码错误", ResultModel.CODE_FAIL);
        }

        [HttpGet]
        public ActionResult logout() 
        {
            HttpContext.Session.Clear();
            return Redirect("/login/index");
        }

        private string generateToken(string username)
        {
            string input = username + DateTime.Now;
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(input));
            return System.Text.Encoding.Default.GetString(result);
        }
    }
}